package com.hitfm.iplay.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.hitfm.iplay.ActivityManger;
import com.hitfm.iplay.MusicInfoController;
import com.hitfm.iplay.MusicPlayerApp;
import com.hitfm.iplay.MusicPlayerService;
import com.hitfm.iplay.R;
import com.hitfm.iplay.db.FavoriteDAO;
import com.hitfm.iplay.ui.VerticalSeekBar;
import com.hitfm.iplay.util.ChangeGradation;
import com.hitfm.iplay.util.ConvertNum;
import com.hitfm.iplay.util.SDCardOperation;

public class PlayingActivity extends Activity {
	private static final String TAG = "iplay";
	private static MusicPlayerService mMusicPlayerService = null;
	private static MusicInfoController mMusicInfoController = null;
	private static String song_name;
	private static String song_singer;
	private static Cursor mCursor = null;
	private static MusicPlayerApp musicPlayerApp;
	private static ServiceConnection mPlaybackConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mMusicPlayerService = ((MusicPlayerService.LocalBinder) service).getService();
			MusicPlayerApp.setmMusicPlayerService(mMusicPlayerService);
		}

		public void onServiceDisconnected(ComponentName className) {
			Log.i(TAG, "Disconnected");
			mMusicPlayerService = null;
		}
	};
	protected static boolean thePlayingSongisDeleted = false;
	private static TextView playing_name;
	private static ImageView playing_status;
	private static ImageView playing_pre;
	private static ImageView playing_next;
	private static com.hitfm.iplay.ui.VerticalSeekBar playing_vol_seekbar;
	private static ImageView playing_vol;
	private static ImageView playing_random;
	private static ImageView albumart;
	private static Handler mHandler = new Handler();
	private static AudioManager mAudioManager;
	private static final int NONEID = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playing);
		findViews();
		initService();
		setListners();
		setPlayingVol();
		ActivityManger.getInstance().addActivity(this);
	}

	Runnable updateUIThread = new Runnable() {

		@Override
		public void run() {
			playAction();
			mHandler.removeCallbacks(updateUIThread);
		}

	};
	protected static float local_movedX;
	protected static float local_movedY;

	static Runnable seekbarThread = new Runnable() {
		// 将要执行的操作写在线程对象的run方法当中
		public void run() {
			playing_vol_seekbar.setVisibility(View.INVISIBLE);
			mHandler.removeCallbacks(seekbarThread);
		};
	};

	static Runnable playProgressThread = new Runnable() {
		// update the playing_seekber's progress and the text of song time
		public void run() {
			try {
				if (isPlayingSeekbarTouch || thePlayingSongisDeleted) {
					return;
				}
				int position = mMusicPlayerService.getPosition();
				int duration = mMusicPlayerService.getDuration();
				int progress = (position * playing_seekbar.getMax()) / duration;
				playing_progress.setText(ConvertNum.milliToSecs(mMusicPlayerService.getPosition()));
				playing_total_time.setText(ConvertNum.milliToSecs(mMusicPlayerService.getDuration()));
				playing_seekbar.setProgress(progress);
				mHandler.post(playProgressThread);
			} catch (Exception e) {
				e.printStackTrace();
			}
		};
	};

	private static TextView playing_total_time;
	private static TextView playing_progress;
	// private ProgressBar playing_progressbar;
	private static android.widget.SeekBar playing_seekbar;
	protected static boolean isPlayingSeekbarTouch = false;
	private static boolean isPause = false;
	protected static boolean isPlaying;
	protected static boolean play_ismoved;
	private static final int MOVEDSC = 20;

	private void setListners() {
		playing_status.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		playing_status.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					local_movedX = event.getX();
					local_movedY = event.getY();
					if (isPlaying) {
						playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(R.drawable.pause));
					} else {
						playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(R.drawable.play));
					}
					break;
				case MotionEvent.ACTION_UP:
					if (PlayingActivity.play_ismoved) {
						if (isPlaying) {
							playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(
									R.drawable.pause_light));
						} else {
							playing_status.setImageDrawable(PlayingActivity.this.getResources()
									.getDrawable(R.drawable.play_light));
						}
					} else {
						if (!SDCardOperation.IsExistSdCard()) {
							Toast.makeText(PlayingActivity.this, R.string.nosdcard, Toast.LENGTH_SHORT).show();
							return false;
						}
						if (isPlaying) {
							playing_status.setImageDrawable(PlayingActivity.this.getResources()
									.getDrawable(R.drawable.play_light));
						} else {
							playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(
									R.drawable.pause_light));
						}
						if (thePlayingSongisDeleted && isPlaying == false) {
							mMusicPlayerService.nextOrPreSong(true);
							isPlaying = true;
							return true;
						}
						/**************************
						 *** 在SD卡被拔出后,再按播放键会报错***
						 **************************/
						if (mMusicPlayerService.isPlaying()) {
							mMusicPlayerService.pause();
							isPlaying = false;
						} else if (null == mMusicPlayerService.getMusicPath() && !mMusicPlayerService.isPlaying()) {
							mMusicPlayerService.nextOrPreSong(true);
							isPlaying = true;
						} else {
							mMusicPlayerService.start();
							isPlaying = true;
						}
					}
					PlayingActivity.play_ismoved = false;
					break;
				case MotionEvent.ACTION_MOVE:
					if (Math.abs((event.getX() - local_movedX)) > MOVEDSC || Math.abs((event.getY() - local_movedY)) > MOVEDSC) {
						PlayingActivity.play_ismoved = true;
					}
					break;
				default:
					break;
				}
				return false;
			}
		});
		playing_next.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mMusicPlayerService.isPlaying() || mMusicPlayerService.isPaused()) {
					mMusicPlayerService.nextOrPreSong(true);
				}
			}
		});
		playing_pre.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mMusicPlayerService.isPlaying() || mMusicPlayerService.isPaused()) {
					mMusicPlayerService.nextOrPreSong(false);
				}
			}
		});
		playing_random.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != mMusicPlayerService) {
					mMusicPlayerService.setRandom(!mMusicPlayerService.isRandom());
				}
				setRandomGradation();
			}
		});
		playing_vol.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// playing_vol_seekbar.setThumb(getResources().getDrawable(R.drawable.playprocess_thumb));
				playing_vol_seekbar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100
						/ mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
				playing_vol_seekbar.setVisibility((View.VISIBLE == playing_vol_seekbar.getVisibility()) ? View.INVISIBLE
						: View.VISIBLE);
				mHandler.postDelayed(seekbarThread, 3000);
			}
		});
		playing_vol_seekbar.setOnSeekBarChangeListener(new com.hitfm.iplay.ui.VerticalSeekBar.OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(VerticalSeekBar VerticalSeekBar) {
				mHandler.postDelayed(seekbarThread, 3000);
			}

			@Override
			public void onStartTrackingTouch(VerticalSeekBar VerticalSeekBar) {
				mHandler.removeCallbacks(seekbarThread);
			}

			@Override
			public void onProgressChanged(VerticalSeekBar VerticalSeekBar, int progress, boolean fromUser) {
				int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
				int index = playing_vol_seekbar.getProgress() * max / playing_vol_seekbar.getMax();
				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, AudioManager.FLAG_PLAY_SOUND);
				setPlayingVol();
			}
		});
		playing_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			// 一次用户更改行为,依次执行start(),changed(),stop();
			int progress = 0;
			boolean fromUser = false;

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				if (fromUser && mMusicPlayerService.isPlaying()) {
					int duration = mMusicPlayerService.getDuration();
					int max = playing_seekbar.getMax();
					int position = (duration * progress) / max;
					mMusicPlayerService.setPosition(position);
				}
				isPlayingSeekbarTouch = false;
				mHandler.post(playProgressThread);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				isPlayingSeekbarTouch = true;
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				this.fromUser = fromUser;
				this.progress = progress;
			}
		});
	}

	protected void setPlayingVol() {
		if (mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
			playing_vol.setImageResource(R.drawable.speaker_mute);
		} else {
			playing_vol.setImageResource(R.drawable.speaker);
		}
	}

	@Override
	protected void onResume() {
		if (isPause) {
			mHandler.post(updateUIThread);
			isPause = false;
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		isPause = true;
		super.onPause();
	}

	private void setRandomGradation() {
		if (null != mMusicPlayerService && mMusicPlayerService.isRandom()) {
			playing_random.setImageDrawable(getResources().getDrawable(R.drawable.random));
		} else {
			playing_random.setImageDrawable(new ChangeGradation().getChangeGradation(getResources()
					.getDrawable(R.drawable.random)));
		}
	}

	private void findViews() {
		playing_name = (TextView) findViewById(R.id.playing_name);
		playing_status = (ImageView) findViewById(R.id.playing_status);
		playing_next = (ImageView) findViewById(R.id.playing_next);
		playing_pre = (ImageView) findViewById(R.id.playing_pre);
		playing_random = (ImageView) findViewById(R.id.playing_random);
		playing_vol = (ImageView) findViewById(R.id.playing_vol);
		playing_vol_seekbar = (com.hitfm.iplay.ui.VerticalSeekBar) findViewById(R.id.playing_vol_seekbar);
		playing_progress = (TextView) findViewById(R.id.playing_progress);
		playing_total_time = (TextView) findViewById(R.id.playing_total_time);
		playing_seekbar = (android.widget.SeekBar) findViewById(R.id.playing_seekBar);
		playing_seekbar.setMax(1000);
		playing_seekbar.setThumb(getResources().getDrawable(R.drawable.playprocess_thumb));
		playing_seekbar.setEnabled(false);
		albumart = (ImageView) findViewById(R.id.albumart);
	}

	protected BroadcastReceiver mPlayerEvtReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 播放器准备完毕或继续播放
			if (action.equals(MusicPlayerService.PLAYER_PREPARE_END) || action.equals(MusicPlayerService.PLAY_CONTINUE)) {
				thePlayingSongisDeleted = false;
				playAction();
			}
			// 播放完成
			else if (action.equals(MusicPlayerService.PLAY_COMPLETED)) {
				playing_name.setText(R.string.playing);
				playing_name.setTextColor(getResources().getColor(R.color.white));
				playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(R.drawable.play_light));
				mMusicPlayerService.nextOrPreSong(mMusicPlayerService.isRandom());
				mHandler.removeCallbacks(seekbarThread);
			}
			// 播放暂停
			else if (action.equals(MusicPlayerService.PLAY_PAUSE)) {
				playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(R.drawable.play_light));
			}
			// 播放异常
			else if (action.equals(MusicPlayerService.ERROR)) {
				mMusicPlayerService.stopPlaying();
				mHandler.removeCallbacks(seekbarThread);
				mHandler.removeCallbacks(playProgressThread);
				playing_status.setImageResource(R.drawable.play);
				playing_seekbar.setEnabled(false);
			} else if (action.equals(MusicPlayerService.UPDATE)) {
				playAction();
			} else if (action.equals(MusicPlayerService.DELETE)) {
				thePlayingSongisDeleted = true;
				playing_name.setText(R.string.playing);
				playing_name.setTextColor(getResources().getColor(R.color.white));
				albumart.setImageResource(R.drawable.default_song_img);
				playing_progress.setText(R.string.zero);
				playing_total_time.setText(R.string.zero);
				playing_status.setImageResource(R.drawable.play);
				playing_seekbar.setProgress(0);
				isPlaying = false;
			}
		}

	};
	private static final int RADIUS15 = 15;
	private static Bitmap albumImage;

	private void playAction() {
		try {
			if (thePlayingSongisDeleted) {
				return;
			}
			if (MusicPlayerService.isUpdate()) {
				mCursor = musicPlayerApp.getAllCursor();
			} else {
				mCursor = musicPlayerApp.getCursor();
			}
			if (null == musicPlayerApp.getCursor()) {
				musicPlayerApp.initCursor();
			}
			if (null == mCursor || null == mMusicPlayerService || null == mMusicPlayerService.getMusicPath()) {
				return;
			}
			mCursor.moveToPosition(mMusicPlayerService.getId());
			song_name = mCursor.getString(mCursor.getColumnIndex(Media.TITLE));
			song_singer = mCursor.getString(mCursor.getColumnIndex(Media.ARTIST));
			if (song_name == null || ("").equals(song_name)) {
				playing_name.setText(mCursor.getString(mCursor.getColumnIndex(Media.DISPLAY_NAME)));
			} else {
				playing_name.setText(mMusicPlayerService.getInfo());
			}
			playing_name.setTextColor(0xFF9370DB);
			if (mMusicPlayerService.isPlaying()) {
				playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(R.drawable.pause_light));
			} else {
				playing_status.setImageDrawable(PlayingActivity.this.getResources().getDrawable(R.drawable.play_light));
			}
			albumImage = mMusicPlayerService.getAlbumArt(NONEID, RADIUS15);
			albumart.setImageBitmap(albumImage);
			mHandler.post(playProgressThread);
			playing_seekbar.setEnabled(true);
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
	}

	protected BroadcastReceiver sdCardReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
				Toast.makeText(PlayingActivity.this, R.string.nosdcard, Toast.LENGTH_SHORT).show();
				mMusicPlayerService.stopPlaying();
				mHandler.removeCallbacks(seekbarThread);
				mHandler.removeCallbacks(playProgressThread);
				playing_status.setImageResource(R.drawable.play);
			} else if (action.endsWith(Intent.ACTION_MEDIA_MOUNTED)) {
				// mMusicPlayerService.onCreate();

			}
		}

	};

	protected void initService() {
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		musicPlayerApp = (MusicPlayerApp) getApplication();
		mMusicInfoController = musicPlayerApp.getMusicInfoController();

		startService(new Intent(this, MusicPlayerService.class));
		getApplicationContext().bindService(new Intent(this, MusicPlayerService.class), mPlaybackConnection,
				Context.BIND_AUTO_CREATE);

		IntentFilter playerFilter = new IntentFilter();
		playerFilter.addAction(MusicPlayerService.PLAYER_PREPARE_END);
		playerFilter.addAction(MusicPlayerService.PLAY_COMPLETED);
		playerFilter.addAction(MusicPlayerService.PLAY_PAUSE);
		playerFilter.addAction(MusicPlayerService.PLAY_CONTINUE);
		playerFilter.addAction(MusicPlayerService.ERROR);
		playerFilter.addAction(MusicPlayerService.UPDATE);
		playerFilter.addAction(MusicPlayerService.DELETE);
		registerReceiver(mPlayerEvtReceiver, playerFilter);

		IntentFilter sdCardFilter = new IntentFilter();
		sdCardFilter.addAction(Intent.ACTION_MEDIA_EJECT);
		sdCardFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		sdCardFilter.addDataScheme("file");
		registerReceiver(sdCardReceiver, sdCardFilter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_play, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// 得到当前选中的MenuItem的ID
		int itemId = item.getItemId();
		switch (itemId) {
		case R.id.addtofavorite:
			if (mMusicPlayerService.getMusicPath() == null) {
				Toast.makeText(PlayingActivity.this, R.string.adderror, Toast.LENGTH_SHORT).show();
				break;
			}
			FavoriteDAO favoriteDAO = new FavoriteDAO(PlayingActivity.this);
			favoriteDAO.open();
			if (favoriteDAO.insertData(mMusicPlayerService.getMusicPath(), MusicPlayerService.getSinger(),
					MusicPlayerService.getSongname(), MusicPlayerService.getAlbum()) != -1) {
				Toast.makeText(PlayingActivity.this, R.string.addok, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(PlayingActivity.this, R.string.adderror, Toast.LENGTH_SHORT).show();
			}
			favoriteDAO.close();
			break;
		case R.id.exit:
			Builder builder = new Builder(PlayingActivity.this);
			builder.setMessage("确认退出吗？");
			builder.setTitle("提示");
			builder.setPositiveButton("确认", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					ActivityManger.getInstance().exit();
				}
			});
			builder.setNegativeButton("取消", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
			break;
		}
		return true;
	}

}
